export interface ICacheData {
	uuid: string;
	type: string;
	asset: cc.Asset
}

export default class ResManager {
	private static _instance: ResManager;
	public static get instance(): ResManager {
		if (!this._instance) {
			this._instance = new ResManager();
		}
		return this._instance;
	}

	public cacheRes: Map<string, ICacheData> = new Map();

	// public cacheSpine: Map<string, cc.Asset> = new Map();

	public get(name: string, type?: any) {
		const cache = this.cacheRes.get(name);
		const asset = cache.asset;
		if (type) {
			if (asset instanceof type) {
				asset.addRef();
				return asset;
			}

			// TODO load
			return null;
		}

		if (asset) {
			asset.addRef();
			return asset;
		}
	}

	// private count: number = 0;
	public set(asset: cc.Asset, type: any) {
		// console.log("asset:", asset, type);

		if (asset.name == '') return;

		const data: ICacheData = {
			uuid: asset['_uuid'],
			type: type,
			asset: asset
		};
		this.cacheRes.set(asset.name, data);

		// this.count++;
		// console.log("assets:", cc.assetManager.assets, cc.assetManager.assets.count, this.count);
		// console.log("cacheRes:", this.cacheRes);
	}

	public remove(name: string) {
		const cache = this.cacheRes.get(name);
		const asset = cc.assetManager.assets.get(cache.uuid);
		if (asset) {
			asset.decRef();
			if (asset.refCount <= 0) {
				cc.assetManager.assets.remove(cache.uuid);
			}
		}

		// console.log("assets:", cc.assetManager.assets, cc.assetManager.assets.count, this.count);
	}

	public clear() {
		this.cacheRes.clear();
	}
}